﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using MvcMusicStore.BI.Client.BI;

namespace MvcMusicStore.BI.Client.Commands
{
  public class LoadSalesCommand : ServiceCommandBase<ISales, SalesClient>
  {
    public static readonly DependencyProperty SalesByMonthProperty =
      DependencyProperty.Register("SalesByMonth", typeof (ObservableCollection<SalesByMonth>), typeof (LoadSalesCommand), new PropertyMetadata(default(BindingList<SalesByMonth>)));

    private int _eventCount;

    public ObservableCollection<SalesByMonth> SalesByMonth
    {
      get { return (ObservableCollection<SalesByMonth>)GetValue(SalesByMonthProperty); }
      set { SetValue(SalesByMonthProperty, value); }
    }

    public static readonly DependencyProperty SalesByGenreProperty =
      DependencyProperty.Register("SalesByGenre", typeof (ObservableCollection<SalesByGenre>), typeof (LoadSalesCommand), new PropertyMetadata(default(ObservableCollection<SalesByGenre>)));

    public ObservableCollection<SalesByGenre> SalesByGenre
    {
      get { return (ObservableCollection<SalesByGenre>) GetValue(SalesByGenreProperty); }
      set { SetValue(SalesByGenreProperty, value); }
    }

    #region Overrides of ServiceCommandBase<ISales,SalesClient>

    protected override bool CanExecute(SalesClient client)
    {
      return true;
    }

    protected override void Execute(SalesClient client)
    {
      Interlocked.Increment(ref _eventCount);
      Interlocked.Increment(ref _eventCount);

      SalesByGenre.Clear();
      SalesByMonth.Clear();

      client.GetSalesByMonthCompleted += ClientOnGetSalesByMonthCompleted;
      client.GetSalesByMonthAsync(this);

      client.GetSalesByGenreCompleted += ClientOnGetSalesByGenreCompleted;
      client.GetSalesByGenreAsync(this);
    }

    private void ClientOnGetSalesByMonthCompleted(object sender, GetSalesByMonthCompletedEventArgs args)
    {
      var wLoadSalesCommand = (SalesClient) sender;
      wLoadSalesCommand.GetSalesByMonthCompleted -= ClientOnGetSalesByMonthCompleted;

      var wSalesCommand = (LoadSalesCommand) args.UserState;
      wSalesCommand.SalesByMonth = args.Result;

      if (Interlocked.Decrement(ref _eventCount) == 0) SetComplete();
    }

    private void ClientOnGetSalesByGenreCompleted(object sender, GetSalesByGenreCompletedEventArgs args)
    {
      var wLoadSalesCommand = (SalesClient)sender;
      wLoadSalesCommand.GetSalesByGenreCompleted -= ClientOnGetSalesByGenreCompleted;

      var wSalesCommand = (LoadSalesCommand)args.UserState;
      wSalesCommand.SalesByGenre = args.Result;

      if (Interlocked.Decrement(ref _eventCount) == 0) SetComplete();
    }

    #endregion
  }
}